﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using Microsoft.Azure.ActiveDirectory.GraphClient;
using Microsoft.Azure.ActiveDirectory.GraphClient.Extensions;
using System.Threading.Tasks;

namespace AzureAD_Schema_Manager
{
    public partial class Form1 : Form
    {
        common com = null;
        ActiveDirectoryClient activeDirectoryClient = null;
        Microsoft.Azure.ActiveDirectory.GraphClient.Application myApp = null;
        private const string FormTitle = "Azure Active Directory Schema Extension Manager";
        private const string PleaseWait = "Please wait...";

        public Form1()
        {
            this.Text = FormTitle;
            InitializeComponent();
            com = new common();
            txtTenantName.Text= com.TenantName;
            txtAppName.Text = com.ApplicationName;
            txtAppClientId.Text = com.ClientId;
            txtAppClientSecret.Text = com.ClientSecret;
        }

        // Initialize
        private void btnConnect_Click(object sender, EventArgs e)
        {
            switchObjectsStatus(false);
            this.Text = PleaseWait + "-" + FormTitle;
            if (txtTenantName.Text.Trim() == "" ||
                txtAppName.Text.Trim() == "" ||
                txtAppClientId.Text.Trim() == "" ||
                txtAppClientSecret.Text.Trim() == "")
            {
                MessageBox.Show("Please provide all parameters to connect");
            }
            else
            {
                try
                {
                    // connect to Azure AD
                    activeDirectoryClient = com.GetActiveDirectoryClientAsApplication(
                        txtTenantName.Text.Trim(),
                        txtAppClientId.Text.Trim(),
                        txtAppClientSecret.Text.Trim());
                    // obtain Application
                    IPagedCollection<IApplication> applications = null;
                    applications = activeDirectoryClient.Applications.Take(999).ExecuteAsync().Result;
                    List<IApplication> appsList = applications.CurrentPage.ToList();
                    foreach (Microsoft.Azure.ActiveDirectory.GraphClient.Application a in appsList)
                    {
                        if (a.DisplayName == txtAppName.Text.Trim())
                        {
                            myApp = a;
                            break;
                        }
                    }
                    if (myApp == null)
                    {
                        MessageBox.Show("Can not obtain application from Azure AD\nApplication Name : " + txtAppName.Text.Trim());
                    }
                    else
                    {
                        // Obtain extended properties from Azure AD
                        foreach (ExtensionProperty p in com.GetExtensions(activeDirectoryClient))
                        {
                            lstExtension.Items.Add(p.Name);
                        }
                        // enable register/remove buttons
                        btnRegister.Enabled = true;
                        btnRemove.Enabled = true;
                        MessageBox.Show("Obtaining current extended schemas complete");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
            this.Text = FormTitle;
            switchObjectsStatus(true);
        }

        private async void button3_Click(object sender, EventArgs e)
        {
            switchObjectsStatus(false);
            this.Text = PleaseWait + "-" + FormTitle;
            if (txtExtensionName.Text.Trim() == "" ||
               txtExtensionTarget.Text.Trim() == "" ||
               txtExtensionType.Text.Trim() == "")
            {
                MessageBox.Show("Please provide extension information to add");
            }
            else
            {
                ExtensionProperty np = new ExtensionProperty();
                np.Name = txtExtensionName.Text.Trim();
                np.DataType = txtExtensionType.Text.Trim();
                np.TargetObjects.Add(txtExtensionTarget.Text.Trim());

                try
                {
                    myApp.ExtensionProperties.Add(np);
                    await myApp.UpdateAsync();
                    // re-Obtain extensions from Azure AD
                    lstExtension.Items.Clear();
                    foreach (ExtensionProperty p in com.GetExtensions(activeDirectoryClient))
                    {
                        lstExtension.Items.Add(p.Name);
                    }
                    txtExtensionType.Text = "";
                    txtExtensionName.Text = "";
                    txtExtensionTarget.Text = "";
                    MessageBox.Show("Registration completed");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
            this.Text = FormTitle;
            switchObjectsStatus(true);
        }

        private void lstExtension_SelectedIndexChanged(object sender, EventArgs e)
        {
            switchObjectsStatus(false);
            this.Text = PleaseWait + "-" + FormTitle;
            foreach (ExtensionProperty p in com.GetExtensions(activeDirectoryClient))
            {
                if (p.Name == (string)lstExtension.SelectedItem)
                {
                    txtExtensionName.Text = p.Name.Substring(p.Name.IndexOf("_",11)+1);
                    txtExtensionType.Text = p.DataType;
                    txtExtensionTarget.Text = p.TargetObjects.FirstOrDefault();
                }
            }
            this.Text = FormTitle;
            switchObjectsStatus(true);
        }

        private void switchObjectsStatus(Boolean enabled)
        {
            foreach (Control c in this.Controls) 
            {
                if (c is Button || c is ListBox)
                {
                    c.Enabled = enabled;
                }
            }
        }

        private async void btnRemove_Click(object sender, EventArgs e)
        {
            switchObjectsStatus(false);
            this.Text = PleaseWait + "-" + FormTitle;
            if (txtExtensionName.Text.Trim() == "" ||
               txtExtensionTarget.Text.Trim() == "" ||
               txtExtensionType.Text.Trim() == "")
            {
                MessageBox.Show("Please provide extension information to remove");
            }
            else
            {
                try
                {
                    // Pattern A : null
                    //IList<ExtensionProperty> exList = myApp.ExtensionProperties;
                    //foreach (ExtensionProperty target in exList)
                    //{
                    //    if (target.Name == (string)lstExtension.SelectedItem)
                    //    {
                    //        myApp.ExtensionProperties.Remove(target);
                    //        await myApp.UpdateAsync();
                    //    }
                    //}

                    // Pattern B : null
                    //ExtensionProperty target = myApp.ExtensionProperties.Where(p => p.Name == (string)lstExtension.SelectedItem).FirstOrDefault();

                    // Pattern C : not null but was not removed
                    foreach (ExtensionProperty target in com.GetExtensions(activeDirectoryClient))
                    {
                        if (target.Name == (string)lstExtension.SelectedItem)
                        {
                            Boolean ret =
                            myApp.ExtensionProperties.Remove(target);
                            await myApp.UpdateAsync();
                            break;
                        }
                    }

                    // re-Obtain extensions from Azure AD
                    lstExtension.Items.Clear();
                    foreach (ExtensionProperty p in com.GetExtensions(activeDirectoryClient))
                    {
                        lstExtension.Items.Add(p.Name);
                    }
                    txtExtensionType.Text = "";
                    txtExtensionName.Text = "";
                    txtExtensionTarget.Text = "";
                    MessageBox.Show("Remove completed");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            this.Text = FormTitle;
            switchObjectsStatus(true);
        }
    }
}
